const Core = require('@alicloud/pop-core');
const jwt = require('jsonwebtoken');

module.exports = {
    sendCode (PhoneNumbers, code) {
        var client = new Core({
            accessKeyId: 'LTAI4GGkKSvRpkWZmT3NXvGb',
            accessKeySecret: 'beSR7GnNScsx9FwpGPavYthTj3jDjQ',
            endpoint: 'https://dysmsapi.aliyuncs.com',
            apiVersion: '2017-05-25'
        });
          
        var params = {
            "RegionId": "cn-hangzhou",
            PhoneNumbers,
            "SignName": "铭心说",
            "TemplateCode": "SMS_202545702",
            "TemplateParam": "{code: "+code+"}"
        }
          
        var requestOption = {
            method: 'POST'
        };
        
        return new Promise((resolve, reject) => {
            client.request('SendSms', params, requestOption).then((result) => {
                console.log(JSON.stringify(result));
                resolve();
            }, (ex) => {
                console.log(ex);
                reject();
            })
        })  
    },
    validateToken(req, res) {
        const token = req.headers.token || req.query.token || req.body.token
        return new Promise(resolve => {
            if(token) {
                jwt.verify(token, 'lmx', (err, decoded) => {
                    if(err) {
                        res.send({
                            code: '10119',
                            message: '无效的token'
                        })
                    } else {
                        req.decoded = decoded
                        resolve()
                    }
                })
            } else {
                res.send({
                    code: '10119',
                    message: '无效的token'
                })
            }
        })
    },
    validateReactToken(req, res) {
        const token = req.headers.token || req.query.token || req.body.token
        return new Promise(resolve => {
            if(token) {
                jwt.verify(token, 'lmx-react', (err, decoded) => {
                    if(err) {
                        res.send({
                            code: '10119',
                            message: '无效的token'
                        })
                    } else {
                        req.decoded = decoded // 保存起来
                        resolve() // token验证成功,返回验证的数据
                    }
                })
            } else {
                res.send({
                    code: '10119',
                    message: '无效的token'
                })
            }
        })
    }
}

